package com.usian.comment.service.impl;

import com.usian.comment.entity.ApComment;
import com.usian.comment.entity.ApCommentLike;
import com.usian.comment.service.CommentService;

import com.usian.comment.vo.CommentVo;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.BeanHelper;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.user.dtos.UserInfoDto;
import com.usian.user.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private GreenTextScan greenTextScan;

    //保存评论
    @Override
    public void saveConment(CommentSaveDto dto) {
        //参数校验
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取用户id，判断是否登录
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null || userId == 0) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //调用阿里云进行文本反垃圾处理
//        try {
//            Map<String, String> map = greenTextScan.greenTextScan(dto.getContent());
//            String suggestion = map.get("suggestion");
//            if (!"pass".equals(suggestion)) {
//                throw new LeadException(AppHttpCodeEnum.TEXT_ILLEGAL);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new LeadException(AppHttpCodeEnum.TEXT_ILLEGAL);
//        }


        //组装评论数据
        UserInfoDto userInfoDto = userFeign.findById(userId);

        ApComment apComment = new ApComment();
        apComment.setAuthorId(userId);
        apComment.setAuthorName(userInfoDto.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(userInfoDto.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType(0);
        apComment.setFlag(0);



        //保存数据
        mongoTemplate.insert(apComment);

    }

    @Override
    public List<CommentVo> loadComment(CommentDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2、获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        //3、设置文章id查询条件
        if(dto.getArticleId()!=null){
            Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
            //4、设置分页条件
            Pageable pageable = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize().intValue());
            query.with(pageable);
            //5、点赞数据条件设置
            if(dto.getMinLikes()!=null && dto.getMinLikes()>0){
                query.addCriteria(Criteria.where("likes").lt(dto.getMinLikes()));
            }

            //6、设置点赞数量降序
            query.with(Sort.by(Sort.Direction.DESC,"likes"));

            //7、执行查询
            List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
            if(CollectionUtils.isEmpty(commentList)){
                throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"评论列表数据不存在");
            }
            //数据转换
            List<CommentVo> commentVoList = BeanHelper.copyWithCollection(commentList, CommentVo.class);

            //用户未登录，直接返回评论列表
            if(userId==null || userId==0){
                return  commentVoList;
            }
            //8、如果用户是登录状态，处理当前登录用户是否对评论进行过点赞操作
            //8.1 查询当前登录用户，是否对评论列表中的评论进行点赞
            List<String> commentIds = commentVoList.stream().map(CommentVo::getId).collect(Collectors.toList());
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("authorId").is(userId).and("commentId").in(commentIds).and("operation").is(0));
            List<ApCommentLike> commentLikeList = mongoTemplate.find(query1, ApCommentLike.class);
            if(!CollectionUtils.isEmpty(commentLikeList)){
                //获取所有当前用户点赞的评论id集合
                List<String> commentLikeIds = commentLikeList.stream().map(ApCommentLike::getCommentId).collect(Collectors.toList());
                //将评论列表返回值CommentVo中的operation设置为0
                commentVoList.stream().forEach(commentVo -> {
                    if(commentLikeIds.contains(commentVo.getId())){
                        commentVo.setOperation(0);
                    }
                });
            }
            return commentVoList;
        }else{
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE,"必须传递文章id");
        }
    }

    @Override
    public void likeComment(CommentLikeDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2、获取用户id，要求用户必须登录才能点赞
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3、查询评论数据是否存在
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(apComment==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"评论数据不存在");
        }
        //4、查询当前用户是否针对这条评论是否点赞过
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(userId));
        ApCommentLike commentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        if(commentLike==null && dto.getOperation()==0 ){
            //4.1 如果未点赞，更新评论的点赞数量，同时记录点赞数据
            commentLike = new ApCommentLike();
            commentLike.setAuthorId(userId);
            commentLike.setCommentId(dto.getCommentId());
            commentLike.setOperation(dto.getOperation());
            mongoTemplate.insert(commentLike);
            //更新评论的点赞数量加一
            Query query1 = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(query1,update,ApComment.class);
        }else if(commentLike!=null && commentLike.getOperation()!=dto.getOperation() ){
            //4.2 如果已经点赞，更新评论的点赞数量，同时更新点赞为状态
            commentLike.setOperation(dto.getOperation());
            mongoTemplate.save(commentLike);

            //更新评论的点赞数量
            Integer opt = dto.getOperation()==0?1:-1;
            if(opt==-1 && apComment.getLikes()<1){
                return;
            }
            Query query1 = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes",opt);
            mongoTemplate.updateFirst(query1,update,ApComment.class);
        }



    }
}
